const { getPassword } = require('../utils/crypto')
const { exec } = require('../db/index')
class UserService {
  async login(ctx) {
    const { username, password, nickname } = ctx.request.body;
    const data = await exec(`select * from users where username=? and password=?`, [username, getPassword(password)]);
    if (data.length) {
      return {
        code: 0,
        msg: '登陆成功',
        data
      }
    } else {
      return {
        code: -1,
        msg: '登陆失败'
      }
    }

  }
  async register(ctx) {
    const { username, password, nickname } = ctx.request.body;
    const data = await exec(`select * from users where username=?`, [username])
    if (!data.length) {
      const data = await exec(`insert into users (username,password,nickname) values (?,?,?)`,
        [username, getPassword(password), nickname])
      return {
        code: 0,
        msg: '注册成功',
        data
      }
    } else {
      return {
        code: -1,
        msg: '此用户已经注册了'
      }
    }
  }
}

module.exports = new UserService